<?php

namespace App\Controller\App;

use App\Base\BaseCache;
use App\Base\BaseController4Restful;
use App\Base\Format;
use App\Entity\Product;
use App\Entity\Shop;
use App\Entity\ShopCategoryApply;
use App\Entity\ShopStatistic;
use App\Entity\User;
use App\Model\LazyCommon\UserModel;
use App\Repository\CategoryRepository;
use App\Repository\ConfigRepository;
use App\Repository\MoneyRepository;
use App\Repository\ShopCategoryApplyRepository;
use App\Repository\ShopRepository;
use App\Repository\ShopTagRepository;
use App\Service\ShopService;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Routing\Annotation\Route;

/**
 * @route("/app")
 */
class ShopController extends BaseController4Restful
{
    /**
     * @Route("/open/shop", name="AppOpenShop")
     */
    public function AppOpenShop()
    {
        $user = $this->getUser();
        if ($shop = $user->getShop()) {
            return $this->json_out(200,"已开通");
        }
        $shop = new Shop();
        $shop->setUser($user)
            ->setName($user->getName()."的店铺")
            ->setPhone($user->getPhone())
            ->setLogo($user->getAvatar())
            ->setIntro("欢迎光临我的店铺！")
            ->setIsAuth(0)
            ->setHead("/ApiCloud/assets/img/banner.jpg")
            ->setOpenStart(0)
            ->setOpenEnd(0)
            ->setOpenStr("全天营业");
        ;

        $this->myEm()->persist($shop);
        $this->myEm()->flush();

        if (!$shop->getStatistic()) {
            $statistic = new ShopStatistic();
            $statistic->setShop($shop)
                ->setIncomes(0)
                ->setOrders(0)
                ->setProducts(0);
            $this->myEm()->persist($statistic);
            $this->myEm()->flush();
        }
//        $this->setGroups("home");
        return $this->json_out(200,"成功开通");
    }
    /**
     * @Route("/shop/home", name="AppShopHome")
     */
    public function AppShopHome()
    {
        $user = $this->getUser();
        $this->setGroups('home');
        $shop = $user->getShop();
        $data["shop"] = $shop;
        $data["statistic"]=$shop->getStatistic();
        return $this->json_out(200,"获取成功",$data);
    }
    /**
     * @Route("/my/shop/info", name="AppMyShopInfo")
     */
    public function AppMyShopInfo()
    {
        $user = $this->getUser();
//        $this->setGroups('home');
        $shop = $user->getShop();
        $data["shop"] = $shop;
//        $data["statistic"]=$shop->getStatistic();
        return $this->json_out(200,"获取成功",$shop);
    }
    /**
     * @Route("/my/shop/{id}", name="AppMyShopUpdate",methods={"POST","PATCH"})
     */
    public function AppMyShopUpdate()
    {
        $data = $this->getRequestData();
        $data["pics"] = json_decode($data["pics"],true);
        $data["head"] = $data["pics"][0];
        $data["phone"] .="";
        $this->setGroups("userEdit");
        $user = $this->getUser();
        $shop = $user->getShop();
        $data["shop"] = $shop;
        /**@var $shop Shop*/
        $shop = $this->updateEntity($data,Shop::class,$shop);
        $this->myEm()->persist($shop);$this->myEm()->flush();
        return $this->json_out(200,"修改成功",$shop);
    }
    /**
     * @Route("/my/shop/cat", name="AppMyShopCategory",methods={"POST","GET"})
     */
    public function AppMyShopCategory(ShopService $shopService)
    {
        $user = $this->needToBeUser();
        $shop = $user->getShop();
        $data = $shopService->getCategoryLimit($shop);
        $this->setGroups("app");
        return $this->json_out(200,"OK",$data);
    }
    /**
     * @Route("/my/shop/cat/apply", name="AppMyShopCategoryApply",methods={"POST","GET"})
     */
    public function AppMyShopCategoryApply(ShopCategoryApplyRepository $shopCategoryApplyRepository,CategoryRepository $categoryRepository)
    {
        if(!$cat1 = $this->getParamRequired("cat1")){return $this->json_out(400,"参数缺失");}
        if(!$cat2 = $this->getParamRequired("cat2")){return $this->json_out(400,"参数缺失");}
        $user = $this->needToBeUser();
        $shop = $user->getShop();
        $shopCats = $shop->getCategories();
        //提交新的审核需要将原有未审核的删除；
        $applyList = $shopCategoryApplyRepository->findBy(array("status"=>"0"));
        foreach ($applyList as $apply) {
            $this->myEm()->remove($apply);
        }
        //处理一级分类
        $cat1Array = myExplodeNumbers($cat1);
        $temParentArr = [];
        foreach ($cat1Array as $id){
            $cat = $categoryRepository->find($id);
//            if (!$shopCats->contains($cat)) {//已经申请到的就不再申请了
                //否则增加一条申请记录
                $ShopCategoryApply = new ShopCategoryApply();
                $ShopCategoryApply->setCreateAt(new \DateTime())
                    ->setStatus(0)
                    ->setCategory($cat)
                    ->setShop($shop);
                $this->myEm()->persist($ShopCategoryApply);
//            }
            //储存一个临时数组，用于检查子分类是否合理：即子分类的父级必须在此数组中
            $temParentArr[] = $cat;
        }

        //处理二级分类
        $cat2Array = myExplodeNumbers($cat2);
        foreach ($cat2Array as $id){
            $cat = $categoryRepository->find($id);
            if (in_array($cat->getParent(),$temParentArr)) {
//                if (!$shopCats->contains($cat)) {//已经申请到的就不再申请了
                    //否则增加一条申请记录
                    $ShopCategoryApply = new ShopCategoryApply();
                    $ShopCategoryApply->setCreateAt(new \DateTime())
                        ->setStatus(0)
                        ->setCategory($cat)
                        ->setShop($shop);
                    $this->myEm()->persist($ShopCategoryApply);
//                }
            }
        }
        $this->myEm()->beginTransaction();
        try {
            $this->myEm()->flush();
        } catch (\Exception $exception) {
            $this->myEm()->rollback();
            return $this->json_out(500,"已提交审核,请耐心等待",$exception);
        }
        $this->myEm()->commit();
        return $this->json_out(200,"已提交审核,请耐心等待");
    }


    /**
     * @Route("/shop/near", name="AppIndexShopList")
     */
    public function AppIndexShopList(ShopRepository $repository)
    {
        $page = $this->getParamRequired("page")?:1;
//        $user = $this->getUser();
//        if (!$user) {return $this->json_out(200,"获取成功",[]);}
        $qb = $repository->createQueryBuilder("A");
        $qb->select("A");
        $qb->where("A.isAuth > 0");
        //todo 这里需要排除一下个人自己发布的店铺

        //地理位置排序
        if (!$lat = $this->getParamRequired("lat")) {$lat = 0;}
        if (!$lon = $this->getParamRequired("lon")) {$lon = 0;}
        if ($lat*$lon) {
//            $qb->addSelect("SQRT(($lat - A.lat)*($lat - A.lat) + ($lon  - A.lon)*($lon  - A.lon)) AS distance");
            $qb->orderBy("SQRT(($lat - A.lat)*($lat - A.lat) + ($lon  - A.lon)*($lon  - A.lon))","ASC");
//            $qb->orderBy("distance","ASC");
        }
        $qb->addOrderBy("A.id","DESC");
        $limit = 10;
        $qb->setMaxResults($limit??10);
        $qb->setFirstResult(($page-1)*$limit);
        $list = $qb->getQuery()->execute();
        $this->setGroups("home");
//        dd($list);
        return $this->json_out(200,"OK",$list);
    }

}
